#include "app_runner.h"
#include "app_serial.h"
#include "app_bluetooth.h"
#include "app_pool.h"
#include "app_router.h"
#include "thirdparty/log/log.h"
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#define SERIAL_DEVICE "/dev/ttyS1"

static SerialDevice serial_device;

static int running = 1;

void app_runner_signalHandler(int signal)
{
    log_info("Received signal %d", signal);
    running = 0;
}

void app_runner_run()
{
    signal(SIGTERM, app_runner_signalHandler);
    signal(SIGINT, app_runner_signalHandler);
    if (app_pool_init(5) < 0)
    {
        log_fatal("Failed to init pool");
        exit(EXIT_FAILURE);
    }

    if (app_serial_init(&serial_device, SERIAL_DEVICE) < 0)
    {
        log_fatal("Failed to init serial device %s", SERIAL_DEVICE);
        exit(EXIT_FAILURE);
    }
    if (app_bluetooth_setConnectionType(&serial_device) < 0)
    {
        log_fatal("Failed to set connection type");
        exit(EXIT_FAILURE);
    }

    if (app_router_init() < 0)
    {
        log_fatal("Failed to init router");
        exit(EXIT_FAILURE);
    }

    if (app_router_registerDevice((Device *)&serial_device) < 0)
    {
        log_error("Failed to register device %s", serial_device.super.filename);
        exit(EXIT_FAILURE);
    }

    while (running)
    {
        usleep(100000);
    }

    app_router_close();
    app_pool_close();
}